package com.lbd.project.service.impl;

import com.lbd.base.service.BaseServiceImpl;
import com.lbd.project.bean.PaybackPlan;
import com.lbd.project.bean.TargetInfo;
import com.lbd.project.controller.vo.TargetVo;
import com.lbd.project.dao.PaybackPlanRepository;
import com.lbd.project.service.PaybackPlanService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by wang on 2016/9/28.
 */
@Service
@Transactional
public class PaybackPlanServiceImpl extends BaseServiceImpl<PaybackPlan, PaybackPlanRepository> implements PaybackPlanService {

    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    PaybackPlanService paybackPlanService;
    @Autowired
    PaybackPlanRepository paybackPlanRepository;

    @Override
    public String buildJpql(PaybackPlan paybackPlan, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  PaybackPlan t   ");
        jpqlBuilder.append("where targetId =:targetId");
        parameter.put("targetId", paybackPlan.getTargetId());
        return jpqlBuilder.toString();
    }


    /**
     * 还款中的项目
     *
     * @param page     页码
     * @param rows     行数
     * @param targetVo 筛选条件
     * @return
     */

   /* @Autowired
    private TargetService targetService;*/

    /**
     * 还款中的项目
     *
     * @param page     页码
     * @param rows     行数
     * @param targetVo 筛选条件
     * @return 还款中的项目
     */
    @Override
    @Transactional(readOnly = true)
    public Page findPayBackList(int page, int rows, TargetVo targetVo) {
        Page<TargetInfo> targetInfoPage = null; /*targetService.findByPageConditionJpql(page, rows, (parameter) -> {
            StringBuilder jpqlBuilder = new StringBuilder(
                    " select new TargetInfo(id, loanNumber, telephone, bdrealname, productid," +
                    " htje, htqx, hkfs, hkqs, lendingDay, targetState) from TargetInfo t ");
            jpqlBuilder.append(" and targetState =:targetState");
            parameter.put("targetState", TargetInfo.TARGET_STATE_PAYBACK);//还款中
            if (targetVo != null) {
                getParams(targetVo, jpqlBuilder, parameter);
                //放款时间区间
                if (null != targetVo.getStartTime()) {
                    jpqlBuilder.append(" and DATE_FORMAT(lending_day,'%Y-%m-%d %H:%i:%s') >=:startTime");
                    parameter.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getStartTime()));
                }
                if (null != targetVo.getEndTime()) {
                    jpqlBuilder.append(" and DATE_FORMAT(lending_day,'%Y-%m-%d %H:%i:%s') <=:endTime");
                    parameter.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getEndTime()));
                }
            }
            jpqlBuilder.append(" order by lending_day desc ");
            return jpqlBuilder.toString();
        });*/
        List<TargetInfo> targetInfoList;
        targetInfoList = targetInfoPage.getContent();
        for (TargetInfo info : targetInfoList) {
            info.setBackAmount("0");
            info.setYhkr(null);
            List<PaybackPlan> paybackPlanList = paybackPlanService.findByTargetIdAndStateInOrderByHkrqAsc(info.getId(),
                    new String[]{"0", "2", "4"});
            PaybackPlan paybackPlan = null;
            if (!paybackPlanList.isEmpty()) {
                paybackPlan = paybackPlanList.get(0);
            }
            if (null != paybackPlan) {
                String bj = paybackPlan.getBj() == null ? "0" : paybackPlan.getBj();
                String lx = paybackPlan.getLx() == null ? "0" : paybackPlan.getLx();
                DecimalFormat df = new DecimalFormat("######0.00");
                info.setBackAmount(df.format(new BigDecimal(bj).add(new BigDecimal(lx))));//总金额
                setYhkrAndRemainderDays(info, paybackPlan);
                info.setQsAll(paybackPlan.getQs() + "/" + info.getHkqs());// 当期应还期数
            }
        }

        return targetInfoPage;
    }

    /**
     * 设置当期应还时间,和剩余天数
     *
     * @param info        标的信息
     * @param paybackPlan 还款计划
     */
    public void setYhkrAndRemainderDays(TargetInfo info, PaybackPlan paybackPlan) {
        Date yhkr = paybackPlan.getYhkr();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(yhkr);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        info.setYhkr(calendar.getTime());//当期应还时间
        if (null != yhkr) {
            long day = (calendar.getTime().getTime() - System.currentTimeMillis()) / (1000 * 60 * 60 * 24);
            info.setRemainderDays(day + "天");//当期剩余天数
        } else {
            info.setRemainderDays("");//当期剩余天数
        }
    }

    /**
     * 还款完成的项目
     *
     * @param page     页码
     * @param rows     行数
     * @param targetVo 筛选条件
     * @return 还款完成的项目
     */
    @Override
    public Page findPayBackFinishList(int page, int rows, TargetVo targetVo) {
        StringBuilder jpqlBuilder = new StringBuilder(
                " SELECT " +
                        " t.id," +
                        " t.loan_number AS loanNumber," +
                        " t.telephone," +
                        " t.bdrealname," +
                        " t.productid," +
                        " t.htje," +
                        " t.htqx," +
                        " t.end_date as endDate," +
                        " DATE_ADD(DATE(t.lending_day),INTERVAL MONTH(NOW())-MONTH(t.`lending_day`) MONTH ) AS lendingDay," +
                        " p.yhkr," +
                        " t.hkqs" +
                        " FROM" +
                        " target_info t ,payback_plan p WHERE t.id=p.target_id and t.hkqs=p.qs and target_state='5'");
        Map<String, Object> parameter = new HashMap();
        if (null != targetVo) {
            getParams(targetVo, jpqlBuilder, parameter);
            //时间区间
            if (null != targetVo.getStartTime()) {
                jpqlBuilder.append(" and t.end_date  >=:startTime");
                parameter.put("startTime", targetVo.getStartTime());
            }
            if (null != targetVo.getEndTime()) {
                jpqlBuilder.append(" and t.end_date  <=:endTime");
                parameter.put("endTime", targetVo.getEndTime());
            }
        }
        jpqlBuilder.append(" order by t.end_date desc");
        return this.findByPageNativeQuery(page, rows, parameter, jpqlBuilder.toString());
    }

    /**
     * 根据id和状态查询还款计划
     *
     * @param id      id
     * @param strings 状态
     * @return
     */
    @Override
    public List<PaybackPlan> findByTargetIdAndStateInOrderByHkrqAsc(String id, String[] strings) {
        return paybackPlanRepository.findByTargetIdAndStateInOrderByHkrqAsc(id, strings);
    }


    //筛选条件拼接
    private void getParams(TargetVo targetVo, StringBuilder jpqlBuilder, Map parameter) {
        //借款类型
        if (StringUtils.isNotBlank(targetVo.getProductid())) {
            jpqlBuilder.append(" and productid = :productid");
            parameter.put("productid", targetVo.getProductid());
        }
        //用户名
        if (StringUtils.isNotBlank(targetVo.getTelephone())) {
            jpqlBuilder.append(" and telephone like:telephone");
            parameter.put("telephone", "%" + targetVo.getTelephone() + "%");
        }
        //真实姓名
        if (StringUtils.isNotBlank(targetVo.getBdrealname())) {
            jpqlBuilder.append(" and bdrealname like:bdrealname");
            parameter.put("bdrealname", "%" + targetVo.getBdrealname() + "%");
        }

        //借款编号
        if (StringUtils.isNotBlank(targetVo.getLoanNumber())) {
            jpqlBuilder.append(" and loan_number like:loanNumber");
            parameter.put("loanNumber", "%" + targetVo.getLoanNumber() + "%");
        }
    }


}
